import React from 'react';
import { Card,Row ,Col ,Modal, Divider, Button, Form, Tree , Select, Spin,Input, Icon, Tabs, InputNumber, message ,Pagination,Tag} from 'antd';
import Utils from './../../../utils/utils';
import './../../../style/style.css';
import './index.less';
import Axios from "../../../axios";
const FormItem = Form.Item;
const TextArea = Input.TextArea;
const TreeNode = Tree.TreeNode;
const Option = Select.Option;
const TabPane = Tabs.TabPane;


export default class OrganDepart extends React.Component {
    state={
        deptJobs:[],
        createDeptModal:{
            visible: false,
            confirmLoading: false,
        },
        delDeptModal:{
            visible: false,
            confirmLoading: false,
        },
    }
    componentWillMount(){
        this.treeDeptRequest();     //查询所有部门【级联数据】
        this.allUserRequest();     //查询所有用户
    }
    //选中操作
    handleOnSelect = (selectedKeys, info) => {
        let selDate = info.node.props.dataRef;  //选中项数据
        let selected = info.selected;       //是否选中
        this.setState({
            selDate,
            selected,
        })
        if (selected) {
            let params = {
                deptId:selDate.id
            }
            this.deptJobsRequest(params);
        }else {
            this.setState({
                deptJobs:[]
            })
        }
    }
    //添加部门 表单弹窗
    handleAddDept = (selDate)=>{
        this.setState({
            createDeptModal:{
                ...this.state.createDeptModal,
                visible: true,
            },
        })
    }
    //添加部门 表单提交
    handleCreateDeptSubmit = ()=>{
        const _form = this.creatDeptForm.props.form;
        _form.validateFields((err, values) => {
            console.log(values);
            if (err) {
                return;
            }
            let params = Utils.FilterParam(values);
            this.createDeptRequest(params);
        });
    }
    //删除部门 表单弹窗
    handleDelDept = (selDate)=>{
        this.setState({
            delDeptModal:{
                ...this.state.delDeptModal,
                visible: true,
            },
        })
    }
    //删除部门 确定
    handleDelDeptSubmit = ()=>{
        const _form = this.delDeptForm.props.form;
        _form.validateFields((err, values) => {
            console.log(values);
            if (err) {
                return;
            }
            let params = Utils.FilterParam(values);
            this.delDeptRequest(params);
        });
    }
    //选中岗位
    handleOnTabClick = (e)=>{
        //console.log(e)
        let params = {
            jobsId:e
        }
        this.jobsUserRequest(params);
    }
    //渲染节点
    renderTreeNodes = (data) => {
       return data.map((item) => {
            if (item.childs.length) {
                return (
                    <TreeNode title={item.name} key={item.id} dataRef={item} icon={<Icon type="team" />}>
                        {this.renderTreeNodes(item.childs)}
                    </TreeNode>
                );
            }
            return <TreeNode title={item.name} key={item.id} dataRef={item} icon={<Icon type="team"/>}/>;
        })
    }

    /*添加部门请求*/
    createDeptRequest = (params)=>{
        this.setState({
            createDeptModal:{
                ...this.state.createDeptModal,
                confirmLoading: true,
            }
        })
        Axios.post({
            block:'/hr',
            url:'/department',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                createDeptModal:{
                    ...this.state.createDeptModal,
                    visible: false,
                }
            },()=>{
                message.success('添加部门成功！',2);
                this.treeDeptRequest();
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                createDeptModal:{
                    ...this.state.createDeptModal,
                    confirmLoading: false,
                }
            })
        })
    }
    /*删除部门请求*/
    delDeptRequest = (params)=>{
        this.setState({
            delDeptModal:{
                ...this.state.delDeptModal,
                confirmLoading: true,
            }
        })
        Axios.delete({
            block:'/hr',
            url:'/department',
            params:params,
        }).then((data)=>{
            console.log(data);
            this.setState({
                delDeptModal:{
                    ...this.state.delDeptModal,
                    visible: false,
                    confirmLoading: false,
                },
                deptJobs:[],
            })
            message.success('删除成功！',2);
            this.treeDeptRequest();
        }).catch((error)=>{
            this.setState({
                delDeptModal:{
                    ...this.state.delDeptModal,
                    visible: false,
                    confirmLoading: false,
                }
            })
            console.log(error);
        })
    }
    /*查询部门挂载的岗位列表*/
    deptJobsRequest = (params)=>{
        Axios.get({
            block:'/hr',
            url:'/jobs/deptJobs',
            params:params,
        }).then((data)=>{
            console.log(data)
            let deptJobs = data.data;
            this.setState({
                deptJobs,
            })
            if (deptJobs.length){
                let params = {
                    jobsId:deptJobs[0].id,
                }
                this.jobsUserRequest(params);
            }
        }).catch((error)=>{
            console.log(error);
        })
    }
    /*查询岗位用户列表*/
    jobsUserRequest = (params)=>{
        Axios.get({
            block:'/hr',
            url:'/jobs/jobsUserList',
            params:params,
        }).then((data)=>{
            console.log(data)
            let jobsUser = data.data;
            this.setState({
                jobsUser,
            })
        }).catch((error)=>{
            console.log(error);
        })
    }



    /*查询所有部门【级联数据】*/
    treeDeptRequest = ()=>{
        this.setState({
            loading:true,
            loadingTxt:'加载中...'
        })
        Axios.get({
            block:'/hr',
            url:'/department/cascade',
            params:'',
        }).then((data)=>{
            console.log(data)
            let treeDeptData = data.data;
            this.setState({
                loading:false,
                treeDeptData,
                //selectedItem:null
            })
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    /*所有用户请求*/
    allUserRequest = ()=>{
        Axios.get({
            block:'/hr',
            url:'/user/allUserSmallInfos',
            params:"",
        }).then((data)=>{
            console.log(data)
            let allUsers = data.data;
            /*id name userNo*/
            this.setState({
                allUsers,
            })
        }).catch((error)=>{
            console.log(error);
        })
    }
    render(){
        const treeDeptData = this.state.treeDeptData||[];
        const selDate = this.state.selDate;
        const selected = this.state.selected;
        const deptJobs = this.state.deptJobs;
        const jobsUser = this.state.jobsUser||[];
        const Toolbar = ()=>{
            if (selected){
                if (selDate.parentId) {
                    return(
                        <div>
                            <a className="btn-txt-primary" onClick={()=>this.handleAddDept(selDate)}>添加下级部门</a>
                            <a className="btn-txt-danger" onClick={()=>this.handleDelDept(selDate)} style={{marginLeft:15}}>删除部门</a>
                        </div>
                    )
                }else {
                    return(
                        <div>
                            <a className="btn-txt-primary" onClick={()=>this.handleAddDept(selDate)}>添加下级部门</a>
                        </div>
                    )
                }
            } else {
                return <div></div>
            }
        }
        const JobsUser = ()=>{
            if (jobsUser.length){
                return(
                    jobsUser.map((item)=>{
                        return <Tag key={item.id}>{item.name}</Tag>
                    })
                )
            }else {
                return <div>该岗位暂未授权用户！</div>
            }
        }
        return(
            <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                <div className="organize-box">
                    <Card title="组织架构" bordered={false}>
                        <Row>
                            <Col sm={6} style={{paddingRight:15}}>
                                <Card title="组织部门" bordered={false} headStyle={{padding:0}} extra={<Toolbar/>}>
                                    {treeDeptData.length
                                        ?
                                        <Tree
                                            showIcon
                                            defaultExpandAll
                                            onSelect={this.handleOnSelect}
                                        >
                                            {this.renderTreeNodes(treeDeptData)}
                                        </Tree>
                                        : '加载中...'}
                                </Card>
                            </Col>
                            <Col sm={18} style={{paddingLeft:15}}>
                                <Card title="岗位人员信息" bordered={false} headStyle={{paddingLeft:0}}>
                                    {
                                        deptJobs.length?
                                            <Tabs
                                                type="card"
                                                onTabClick={this.handleOnTabClick}
                                            >
                                                {
                                                    deptJobs.map((item)=>{
                                                        return(
                                                            <TabPane tab={item.name} key={item.id}><JobsUser/></TabPane>
                                                        )
                                                    })
                                                }
                                            </Tabs>
                                            :<div>暂无岗位信息</div>
                                    }
                                    {/*<Tabs
                                        type="card"
                                    >
                                        <TabPane tab="岗位1" key="1">Content of Tab Pane 1</TabPane>
                                        <TabPane tab="岗位2" key="2">Content of Tab Pane 2</TabPane>
                                        <TabPane tab="岗位3" key="3">Content of Tab Pane 3</TabPane>
                                    </Tabs>*/}
                                </Card>
                            </Col>
                        </Row>
                    </Card>
                    <Modal title="添加下级部门"
                           visible={this.state.createDeptModal.visible}
                           onOk={this.handleCreateDeptSubmit}
                           okText="确定"
                           confirmLoading={this.state.createDeptModal.confirmLoading}
                           onCancel={()=>{
                               this.setState({
                                   createDeptModal:{
                                       visible:false
                                   }
                               })
                           }}
                    >
                        <CreatDeptForm
                            selDate={this.state.selDate}
                            allUsers={this.state.allUsers}
                            wrappedComponentRef={(creatDeptForm)=>{this.creatDeptForm = creatDeptForm;}}/>
                    </Modal>
                    <Modal title="确定删除部门"
                           visible={this.state.delDeptModal.visible}
                           onOk={this.handleDelDeptSubmit}
                           okText="确定删除"
                           confirmLoading={this.state.delDeptModal.confirmLoading}
                           onCancel={()=>{
                               this.setState({
                                   delDeptModal:{
                                       visible:false
                                   }
                               })
                           }}
                    >
                        <DelDeptForm
                            selDate={this.state.selDate}
                            wrappedComponentRef={(delDeptForm)=>{this.delDeptForm = delDeptForm;}}/>
                    </Modal>
                </div>
            </Spin>
        )
    }
}

//添加下级部门表单
class CreatDeptForm extends React.Component{
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 16}
        };
        const allUsers = this.props.allUsers || [];
        const selDate = this.props.selDate;
        const userOptions = allUsers.map((item)=>{
            return <Option key={item.id}>{item.name}</Option>;
        });
        return (
                <Form>
                    <FormItem label="父级部门编号" {...formItemLayout} style={{display:"none"}}>
                        {
                            getFieldDecorator('parentId',{
                                initialValue:selDate.id
                            })(
                                <Input type="text" placeholder="父级部门编号"/>
                            )
                        }
                    </FormItem>
                    <FormItem label="部门名称" {...formItemLayout}>
                        {
                            getFieldDecorator('name',{
                                rules: [{ required: true, message: '请填写部门名称!' }],
                            })(
                                <Input type="text" placeholder="部门名称"/>
                            )
                        }
                    </FormItem>
                    <FormItem label="部门级别" {...formItemLayout}>
                        {
                            getFieldDecorator('level',{
                                rules: [{ required: true, message: '请填写部门级别!' }],
                            })(
                                <InputNumber max={10} min={1} placeholder="部门级别" style={{width:"100%"}}/>
                            )
                        }
                    </FormItem>
                    <FormItem label="部门leader" {...formItemLayout}>
                        {
                            getFieldDecorator('leaderUserId',{
                                rules: [{ required: true, message: '请选择部门leader!' }],
                            })(
                                <Select
                                    placeholder="请选择部门leader"
                                    /*labelInValue*/
                                    style={{ minWidth: 160 }}
                                    showSearch
                                    optionFilterProp="children"
                                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                >
                                    {userOptions}
                                </Select>
                            )
                        }
                    </FormItem>
                    <FormItem label="部门描述" {...formItemLayout}>
                        {
                            getFieldDecorator('description',{
                            })(
                                <TextArea placeholder="部门描述" autosize/>
                            )
                        }
                    </FormItem>
                </Form>
        );
    }
}
CreatDeptForm = Form.create({})(CreatDeptForm);
//删除部门表单
class DelDeptForm extends React.Component{
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 5},
            wrapperCol: {span: 16}
        };
        const selDate = this.props.selDate;
        return (
            <Form>
                <div style={{textAlign:"center",marginBottom:15}} className="txt-danger">确定删除部门 <span className="txt-success">{selDate.name}</span>？删除后数据不可恢复！</div>
                <FormItem label="部门编号" {...formItemLayout} style={{display:"none"}}>
                    {
                        getFieldDecorator('id',{
                            initialValue:selDate.id
                        })(
                            <Input type="text" placeholder="部门编号"/>
                        )
                    }
                </FormItem>
                <FormItem label="备注" {...formItemLayout}>
                    {
                        getFieldDecorator('remark',{
                        })(
                            <TextArea placeholder="备注信息" autosize/>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
DelDeptForm = Form.create({})(DelDeptForm);
